﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Tarea5
{
    class ModelTTTHH : ModelBase
    {
        private StateTTT state;

        override public void Initialize(int sleepInterval, int size, bool HumanMakesFirstMove)
        {
            base.Initialize(sleepInterval, size, HumanMakesFirstMove);
            state = new StateTTT(this.size);
            if(!HumanMakesFirstMove) MakeComputerMove();
        }

        override protected void ModelStart()
        {
            ///VOID METHOD, NO ALGORITHM IN INTERACTIVE MODE!
        }

        private int MakeComputerMove()
        {
            int row, col;

            GenerateRandomPosition(row, col);

            StateTTT tmp = state.GetNextState(row, col, nextTurnIsCrossPlayerS);

            if (tmp == null) return -1;
            nextTurnIsCrossPlayerS = !nextTurnIsCrossPlayerS;
            state = tmp;
            NotifyAll(this.state, "", "");

            if (state.IsWon)
            {
                NotifyAll(this.state, "Computer has won!", "");
                return this.state.Index;
            }
            else if (state.Index == state.Board.Length)
            {
                NotifyAll(this.state, "Tie!", "");
                return this.state.Index;
            }

            return this.state.Index;
        }

        override public int SetPosition(int row, int col) 
        {
            StateTTT tmp = state.GetNextState(row, col, nextTurnIsCrossPlayerS);

            if (tmp == null) return -1;
            nextTurnIsCrossPlayerS = !nextTurnIsCrossPlayerS;
            state = tmp;
            NotifyAll(this.state, "", "");

            if(state.IsWon)
            {
                NotifyAll(this.state, "Human has won!", "");
                return this.state.Index;
            }
            else if (state.Index == state.Board.Length)
            {
                NotifyAll(this.state, "Tie!", "");
                return this.state.Index;
            }

            return MakeComputerMove();
        }

        private void GenerateRandomPosition(ref int row, ref int col)
        {
            Random rand = new Random();
            
            int randRow, randCol;

            do
            {
                randRow = rand.Next(state.Board.GetLength(0));
                randCol = rand.Next(state.Board.GetLength(0));
            }
            while (state.Board[randRow, randCol] != 0);

            row = randRow;
            col = randCol;
        }

        override public int UnsetLastPosition() { }

        override public void Start() { }

        override public void Pause() { }

        override public void Stop() { }
    }
}
